<?php

namespace app\admin\controller\community;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 社区管理
 *
 * @icon fa fa-file
 */
class Community extends Backend
{

    /**
     * Community模型对象
     */
    protected $model = null;
    protected $noNeedRight = ["lists", "status", "test"];
    protected $noNeedLogin = ["lists", "status", "test"];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Community');
        $this->modelValidate = true;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            // 如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 获取城市和学校过滤参数
            $city_id = $this->request->get("city_id");
            $school_id = $this->request->get("school_id");

            // 调试日志
            error_log("Community Index - city_id: $city_id, school_id: $school_id");

            $total = $this->model
                ->where($where);

            // 添加城市过滤
            if (!empty($city_id)) {
                $total = $total->where("city_id", "=", $city_id);
            } else if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 2) {
                $total = $total->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }

            // 添加学校过滤（社区可能关联学校）
            if (!empty($school_id)) {
                // 查找与该学校相关的社区
                $total = $total->where("school_id", "=", $school_id);
            }

            $total = $total->where("status", "<>", -1)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where);

            // 添加城市过滤
            if (!empty($city_id)) {
                $list = $list->where("city_id", "=", $city_id);
            } else if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 2) {
                $list = $list->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }

            // 添加学校过滤（社区可能关联学校）
            if (!empty($school_id)) {
                // 查找与该学校相关的社区
                $list = $list->where("school_id", "=", $school_id);
            }

            $list = $list->where("status", "<>", -1)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $key=>$item) {
                $list[$key]["city_id"]=model("Cityarea")->getCity_idTextAttr($item["city_id"]);
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    // 是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    // 添加成功后，自动更新所有社区的课程代码
                    $this->updateAllCommunityCourseCode();
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                try {
                    // 是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ?
                            ($this->modelSceneValidate ? $name . '.edit' : $name) :
                            $this->modelValidate;
                    }

                    $datatime = date("Y-m-d H:i:s");
                    $params['update_time'] = $datatime;
                    unset($params['delete_time']);
                    unset($params['create_time']);
                    $result = $row->allowField(true)->save($params);

                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter'));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                // 删除成功后，自动更新所有社区的课程代码
                $this->updateAllCommunityCourseCode();

                // 删除后，重新排序
                // 这里假设有 project_id 参数传递
                $projectId = $this->request->post('project_id');
                if ($projectId) {
                    $courseCodes = $this->model->where(['project_id' => $projectId])->order('id asc')->select();
                    foreach ($courseCodes as $k => $row) {
                        $this->model->where('id', $row['id'])->update(['code' => '社区' . ($k + 1)]);
                    }
                }

                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function findCommunityId($ocation_id)
    {
        // 先直接查询
        $community_id = Db::name('eb_school_community')
            ->where('ocation_id', $ocation_id)
            ->value('community_id');

        if ($community_id) {
            return $community_id;
        }

        // 如果没有直接记录，通过父级教学点递归查找
        return $this->findCommunityIdRecursive($ocation_id);
    }

    /**
     * 测试 findCommunityId 方法
     * 访问: /admin/community/community/testFindCommunityId?ocation_id=260
     */
    public function testFindCommunityId()
    {
        $ocation_id = $this->request->param('ocation_id', 260);

        $start_time = microtime(true);

        // 调用方法
        $community_id = $this->findCommunityId($ocation_id);

        $end_time = microtime(true);
        $execution_time = round(($end_time - $start_time) * 1000, 2);

        // 查询社区信息
        $community_info = null;
        if ($community_id) {
            $community_info = Db::name('fa_community')
                ->where('id', $community_id)
                ->find();
        }

        // 查询教学点信息
        $ocation_info = Db::name('fa_ocation')
            ->where('id', $ocation_id)
            ->find();

        $result = [
            'test_info' => [
                'ocation_id' => $ocation_id,
                'execution_time' => $execution_time . 'ms',
                'method' => 'Community::findCommunityId()',
                'test_time' => date('Y-m-d H:i:s')
            ],
            'ocation_info' => $ocation_info,
            'result' => [
                'community_id' => $community_id,
                'found' => $community_id ? true : false
            ],
            'community_info' => $community_info
        ];

        return json([
            'code' => 1,
            'msg' => $community_id ? '测试成功，找到社区ID' : '测试完成，未找到社区ID',
            'data' => $result
        ]);
    }

    /**
     * 获取社区列表
     */
    public function lists()
    {
        $cityId = $this->request->get('cityId', 0);
        $school_id = $this->request->get('school_id', 0);

        // 如果有学校ID筛选，需要使用JOIN查询
        if ($school_id > 0) {
            $list = Db::name('fa_community')
                ->alias('c')
                ->join('eb_school_community sc', 'c.id = sc.community_id')
                ->where('c.status', 1)
                ->where('c.delete_time', null)
                ->where('sc.school_id', $school_id)
                ->field('c.id, c.name')
                ->order('c.weigh desc, c.id asc')
                ->select();
        } else {
            // 普通查询
            $query = Db::name('fa_community')
                ->where('status', 1);

            // 如果有城市ID筛选
            if ($cityId > 0) {
                $query->where('city_id', $cityId);
            }

            $list = $query->field('id, name')
                ->order('weigh desc, id asc')
                ->select();
        }

        $result = [
            'code' => 1,
            'msg' => 'success',
            'list' => $list
        ];

        return json_encode($result);
    }

    /**
     * 递归查找父级教学点的community_id
     */
    private function findCommunityIdRecursive($ocation_id, $depth = 0)
    {
        // 防止无限递归，最多查找5层
        if ($depth > 8 || empty($ocation_id)) {
            return null;
        }

        // 查询当前教学点的父级ID
        $parent_id = Db::name('fa_ocation')
            ->where('id', $ocation_id)
            ->value('pid');

        if (!$parent_id) {
            return null;
        }

        // 查询父级教学点是否有对应的社区ID
        $community_id = Db::name('eb_school_community')
            ->where('ocation_id', $parent_id)
            ->value('community_id');

        if ($community_id) {
            return $community_id;
        }

        // 如果父级也没有，继续向上查找
        return $this->findCommunityIdRecursive($parent_id, $depth + 1);
    }
}
